<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>QuantAgent - Multi-Agent Trading System</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
                 :root {
             --etrade-purple: #241056;
             --etrade-purple-light: #5627D8;
             --etrade-purple-dark: #1A0B3A;
             --etrade-purple-bg: #F8F5FF;
            --white: #ffffff;
            --gray-50: #F9FAFB;
            --gray-100: #F3F4F6;
            --gray-200: #E5E7EB;
            --gray-300: #D1D5DB;
            --gray-400: #9CA3AF;
            --gray-500: #6B7280;
            --gray-600: #4B5563;
            --gray-700: #374151;
            --gray-800: #1F2937;
            --gray-900: #111827;
        }

        * {
            box-sizing: border-box;
            border-width: 0;
            border-style: solid;
            border-color: #e5e7eb;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--etrade-purple-bg);
            color: var(--gray-800);
            line-height: 1.6;
            margin: 0;
            padding: 0;
        }

        .flex { display: flex; }
        .flex-col { flex-direction: column; }
        .min-h-screen { min-height: 100vh; }
        .overflow-hidden { overflow: hidden; }
        .absolute { position: absolute; }
        .relative { position: relative; }
        .w-full { width: 100%; }
        .z-30 { z-index: 30; }
        .max-w-6xl { max-width: 72rem; }
        .mx-auto { margin-left: auto; margin-right: auto; }
        .px-4 { padding-left: 1rem; padding-right: 1rem; }
        .sm\:px-6 { padding-left: 1.5rem; padding-right: 1.5rem; }
        .items-center { align-items: center; }
        .justify-between { justify-content: space-between; }
        .h-16 { height: 4rem; }
        .md\:h-20 { height: 5rem; }
        .shrink-0 { flex-shrink: 0; }
        .mr-4 { margin-right: 1rem; }
        .grow { flex-grow: 1; }
        .justify-end { justify-content: flex-end; }
        .flex-wrap { flex-wrap: wrap; }
        .ml-3 { margin-left: 0.75rem; }
        .block { display: block; }
        .text-slate-100 { color: #f1f5f9; }
        .bg-slate-800 { background-color: #1e293b; }
        .hover\:bg-slate-900:hover { background-color: #0f172a; }
        .group { }
        .shadow-sm { box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); }
        .inline-flex { display: inline-flex; }
        .tracking-normal { letter-spacing: 0; }
        .text-etrade-purple { color: var(--etrade-purple); }
        .group-hover\:translate-x-0\.5:hover { transform: translateX(0.125rem); }
        .transition-transform { transition-property: transform; }
        .duration-150 { transition-duration: 150ms; }
        .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); }
        .ml-2 { margin-left: 0.5rem; }
        .fill-current { fill: currentColor; }
        .grow { flex-grow: 1; }
        .pt-36 { padding-top: 9rem; }
        .md\:pt-40 { padding-top: 10rem; }
        .md\:pb-20 { padding-bottom: 5rem; }
        .max-w-xl { max-width: 36rem; }
        .md\:max-w-none { max-width: none; }
        .text-center { text-align: center; }
        .md\:text-left { text-align: left; }
        .md\:w-\[600px\] { width: 600px; }
        .h1 { font-size: 3rem; font-weight: 700; line-height: 1.2; }
        .text-white { color: #ffffff; }
        .mb-6 { margin-bottom: 1.5rem; }
        .text-lg { font-size: 1.125rem; line-height: 1.75rem; }
        .text-etrade-purple-light { color: var(--etrade-purple-light); }
        .mb-8 { margin-bottom: 2rem; }
        .max-w-xs { max-width: 20rem; }
        .sm\:max-w-none { max-width: none; }
        .sm\:flex { display: flex; }
        .sm\:justify-center { justify-content: center; }
        .md\:justify-start { justify-content: flex-start; }
        .space-y-4 > * + * { margin-top: 1rem; }
        .sm\:space-y-0 > * + * { margin-top: 0; }
        .sm\:space-x-4 > * + * { margin-left: 1rem; }
        .mb-12 { margin-bottom: 3rem; }
        .md\:mb-0 { margin-bottom: 0; }
        .w-full { width: 100%; }
        .bg-gradient-to-tr { background-image: linear-gradient(to top right, var(--tw-gradient-stops)); }
        .from-etrade-purple { --tw-gradient-from: var(--etrade-purple); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(92, 45, 145, 0)); }
        .to-etrade-purple-light { --tw-gradient-to: var(--etrade-purple-light); }
        .shadow-sm { box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); }
        .relative { position: relative; }
        .before\:absolute::before { position: absolute; }
        .before\:inset-0::before { top: 0; right: 0; bottom: 0; left: 0; }
        .before\:bg-etrade-purple::before { background-color: var(--etrade-purple); }
        .before\:bg-opacity-60::before { --tw-bg-opacity: 0.6; }
        .before\:-z-10::before { z-index: -10; }
        .before\:rounded-full::before { border-radius: 9999px; }
        .rounded-full { border-radius: 9999px; }
        .hover\:bg-etrade-purple-light:hover { background-color: var(--etrade-purple-light); }

        /* Header */
        header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid var(--gray-200);
        }

        /* Hero Section */
        .hero-section {
            background: linear-gradient(135deg, var(--etrade-purple) 0%, var(--etrade-purple-light) 100%);
            position: relative;
            overflow: hidden;
        }

        .hero-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/><circle cx="10" cy="60" r="0.5" fill="white" opacity="0.1"/><circle cx="90" cy="40" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.3;
        }

        /* Form Styles */
                 .form-container {
             background: var(--white);
             border-radius: 20px;
             box-shadow: 0 25px 50px -12px rgba(36, 16, 86, 0.25);
             margin: 2rem auto;
             max-width: 1200px;
             overflow: hidden;
         }

        .form-section {
            padding: 3rem 2rem;
            background: var(--white);
        }

        .form-section h3 {
            color: var(--etrade-purple);
            font-weight: 600;
            margin-bottom: 2rem;
            font-size: 1.5rem;
        }

        .form-control, .form-select {
            border: 2px solid var(--gray-200);
            border-radius: 12px;
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            background: var(--white);
            width: 100%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--etrade-purple);
            box-shadow: 0 0 0 3px rgba(36, 16, 86, 0.1), 0 4px 12px rgba(36, 16, 86, 0.1);
            outline: none;
            transform: translateY(-1px);
        }
        
        .form-control:hover, .form-select:hover {
            border-color: var(--gray-300);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        /* Glow or Gradient Border on Active Fields */
        input[type="time"]:focus, input[type="date"]:focus {
            border: 1px solid #9b6bff;
            box-shadow: 0 0 0 2px rgba(155, 107, 255, 0.2);
            transition: all 0.2s ease-in-out;
        }

        .form-label {
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
            display: block;
        }

                 .btn-primary {
             background: var(--etrade-purple-light);
             border: none;
             border-radius: 12px;
             padding: 1rem 2rem;
             font-weight: 600;
             font-size: 1.1rem;
             color: var(--white);
             transition: all 0.3s ease;
             box-shadow: 0 4px 15px rgba(86, 39, 216, 0.3);
             cursor: pointer;
         }

         .btn-primary:hover {
             transform: translateY(-2px);
             box-shadow: 0 8px 25px rgba(86, 39, 216, 0.4);
             background: var(--etrade-purple);
         }
         
         .btn-primary:disabled {
             opacity: 0.7;
             cursor: not-allowed;
             transform: none;
         }
         
         /* Enhanced Button Styles */
         .btn {
             display: inline-flex;
             align-items: center;
             justify-content: center;
             gap: 0.5rem;
             padding: 0.75rem 1.5rem;
             border: none;
             border-radius: 12px;
             font-weight: 600;
             font-size: 0.95rem;
             text-decoration: none;
             cursor: pointer;
             transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
             position: relative;
             overflow: hidden;
             box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
         }
         
         .btn::before {
             content: '';
             position: absolute;
             top: 0;
             left: -100%;
             width: 100%;
             height: 100%;
             background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
             transition: left 0.5s;
         }
         
         .btn:hover::before {
             left: 100%;
         }
         
         .btn-outline-primary {
             background: transparent;
             color: var(--etrade-purple);
             border: 2px solid var(--etrade-purple);
             box-shadow: 0 2px 8px rgba(36, 16, 86, 0.1);
         }
         
         .btn-outline-primary:hover {
             background: var(--etrade-purple);
             color: var(--white);
             transform: translateY(-2px);
             box-shadow: 0 8px 20px rgba(36, 16, 86, 0.3);
         }
         
         .btn-outline-primary:active {
             transform: translateY(0);
             box-shadow: 0 4px 12px rgba(36, 16, 86, 0.2);
         }
         
         .btn-outline-primary:disabled {
             opacity: 0.6;
             cursor: not-allowed;
             transform: none;
             box-shadow: 0 2px 8px rgba(36, 16, 86, 0.1);
         }
         
         .btn-outline-primary:disabled:hover {
             background: transparent;
             color: var(--etrade-purple);
             transform: none;
             box-shadow: 0 2px 8px rgba(36, 16, 86, 0.1);
         }
         
         .fa-spin {
             animation: fa-spin 2s infinite linear;
         }
         
         @keyframes fa-spin {
             0% { transform: rotate(0deg); }
             100% { transform: rotate(360deg); }
         }

        .alert {
            border-radius: 12px;
            border: none;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

                 .alert-info {
             background: linear-gradient(135deg, rgba(36, 16, 86, 0.1) 0%, rgba(86, 39, 216, 0.1) 100%);
             border-left: 4px solid var(--etrade-purple);
             color: var(--gray-700);
         }

        .alert-warning {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(251, 191, 36, 0.1) 100%);
            border-left: 4px solid #F59E0B;
            color: #92400E;
        }

        .alert-danger {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(248, 113, 113, 0.1) 100%);
            border-left: 4px solid #EF4444;
            color: #991B1B;
        }

        .row { display: flex; flex-wrap: wrap; margin-left: -0.75rem; margin-right: -0.75rem; }
        .col-md-6 { flex: 0 0 50%; max-width: 50%; padding-left: 0.75rem; padding-right: 0.75rem; }
        .col-md-4 { flex: 0 0 33.333333%; max-width: 33.333333%; padding-left: 0.75rem; padding-right: 0.75rem; }
        .col-md-12 { flex: 0 0 100%; max-width: 100%; padding-left: 0.75rem; padding-right: 0.75rem; }
        .mb-4 { margin-bottom: 1.5rem; }
        .mb-3 { margin-bottom: 1rem; }
        .mt-2 { margin-top: 0.5rem; }
        .mt-3 { margin-top: 1rem; }
        .text-center { text-align: center; }
        .fw-bold { font-weight: 600; }
        .text-muted { color: var(--gray-500) !important; }
        .d-flex { display: flex; }
        .align-items-center { align-items: center; }
        .justify-content-center { justify-content: center; }
        .w-100 { width: 100%; }
        .h-100 { height: 100%; }
        .visually-hidden { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0, 0, 0, 0) !important; white-space: nowrap !important; border: 0 !important; }

                 .form-check-input:checked {
             background-color: var(--etrade-purple);
             border-color: var(--etrade-purple);
         }

         .form-check-input:focus {
             border-color: var(--etrade-purple);
             box-shadow: 0 0 0 0.25rem rgba(36, 16, 86, 0.25);
         }

        .form-check {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .form-check-input {
            margin-right: 0.5rem;
        }

        .form-check-label {
            margin-bottom: 0;
        }

                 .me-3 { margin-right: 0.75rem; }
         .mt-1 { margin-top: 0.25rem; }
         
         /* Asset Button Grid Styles */
         .asset-button-grid {
             display: grid;
             grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
             gap: 0.75rem;
             margin-top: 0.5rem;
         }
         
         .asset-btn {
             background: var(--gray-100);
             border: 2px solid var(--gray-200);
             border-radius: 16px;
             padding: 1rem 0.75rem;
             font-weight: 600;
             font-size: 1rem;
             color: var(--gray-700);
             transition: all 0.3s ease;
             cursor: pointer;
             display: flex;
             flex-direction: column;
             align-items: center;
             gap: 0.5rem;
             min-height: 80px;
             justify-content: center;
         }
         
         .asset-btn:hover {
             background: var(--gray-200);
             border-color: var(--etrade-purple-light);
             transform: translateY(-2px);
             box-shadow: 0 4px 12px rgba(86, 39, 216, 0.15);
         }
         
         .asset-btn.active {
             background: var(--etrade-purple-light);
             border-color: var(--etrade-purple-light);
             color: var(--white);
             transform: translateY(-2px);
             box-shadow: 0 8px 20px rgba(86, 39, 216, 0.3);
         }
         
         .asset-btn i {
             font-size: 1.5rem;
             margin-bottom: 0.25rem;
         }
         
         .custom-asset-btn {
             background: linear-gradient(135deg, var(--gray-100) 0%, var(--gray-200) 100%);
             border: 2px dashed var(--gray-400);
         }
         
         .custom-asset-btn:hover {
             background: linear-gradient(135deg, var(--etrade-purple-light) 0%, var(--etrade-purple) 100%);
             border-color: var(--etrade-purple-light);
             color: var(--white);
         }
         
         .input-group {
             display: flex;
             gap: 0.75rem;
             align-items: stretch;
         }
         
         .input-group .form-control {
             flex: 1;
             border-radius: 12px;
             border: 2px solid var(--gray-200);
             padding: 0.75rem 1rem;
             font-size: 0.95rem;
             transition: all 0.3s ease;
         }
         
         .input-group .form-control:focus {
             border-color: var(--etrade-purple);
             box-shadow: 0 0 0 3px rgba(36, 16, 86, 0.1);
             outline: none;
         }
         
         .input-group .btn {
             border-radius: 12px;
             white-space: nowrap;
             min-width: 100px;
         }

         /* Panel Layout Styles */
         .panel-group {
             display: grid;
             grid-template-columns: 1fr 1fr;
             gap: 2rem;
             margin-bottom: 2rem;
         }
         
         .panel {
             background: var(--white);
             border: 2px solid var(--gray-200);
             border-radius: 16px;
             padding: 1.5rem;
             box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
             transition: all 0.3s ease;
         }
         
         .panel:hover {
             border-color: var(--etrade-purple-light);
             box-shadow: 0 8px 24px rgba(86, 39, 216, 0.1);
         }
         
         .panel-title {
             color: var(--etrade-purple);
             font-weight: 600;
             font-size: 1.4rem;
             margin: 0.5rem 0 1.5rem 0;
             padding-bottom: 0.5rem;
             border-bottom: 2px solid var(--gray-100);
             display: flex;
             align-items: center;
             justify-content: center;
             gap: 0.75rem;
         }
         
         .panel-title i {
             font-size: 1.5rem;
             color: var(--etrade-purple-light);
             background: linear-gradient(135deg, var(--etrade-purple-light) 0%, var(--etrade-purple) 100%);
             -webkit-background-clip: text;
             -webkit-text-fill-color: transparent;
             background-clip: text;
             filter: drop-shadow(0 2px 4px rgba(86, 39, 216, 0.2));
         }
         
         .action-panel .panel-title {
             color: var(--white);
             border-bottom-color: rgba(255, 255, 255, 0.2);
         }
         
         .action-panel .panel-title i {
             color: var(--white);
             background: linear-gradient(135deg, var(--white) 0%, rgba(255, 255, 255, 0.8) 100%);
             -webkit-background-clip: text;
             -webkit-text-fill-color: transparent;
             background-clip: text;
             filter: drop-shadow(0 2px 4px rgba(255, 255, 255, 0.3));
         }
         
         /* Modern Hero Button */
         .hero-btn {
             display: inline-flex;
             align-items: center;
             gap: 1rem;
             background: linear-gradient(135deg, var(--etrade-purple-light) 0%, var(--etrade-purple) 100%);
             color: var(--white);
             padding: 1.25rem 2.5rem;
             border-radius: 50px;
             text-decoration: none;
             font-weight: 600;
             font-size: 1.1rem;
             transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
             box-shadow: 0 8px 25px rgba(86, 39, 216, 0.3);
             position: relative;
             overflow: hidden;
         }
         
         .hero-btn::before {
             content: '';
             position: absolute;
             top: 0;
             left: -100%;
             width: 100%;
             height: 100%;
             background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
             transition: left 0.6s;
         }
         
         .hero-btn:hover::before {
             left: 100%;
         }
         
         .hero-btn:hover {
             transform: translateY(-3px);
             box-shadow: 0 12px 35px rgba(86, 39, 216, 0.4);
             background: linear-gradient(135deg, var(--etrade-purple) 0%, var(--etrade-purple-light) 100%);
         }
         
         .hero-btn:active {
             transform: translateY(-1px);
             box-shadow: 0 6px 20px rgba(86, 39, 216, 0.3);
         }
         
         .hero-btn-text {
             position: relative;
             z-index: 1;
         }
         
         .hero-btn-icon {
             position: relative;
             z-index: 1;
             transition: transform 0.3s ease;
         }
         
         .hero-btn:hover .hero-btn-icon {
             transform: translateX(4px);
         }
         
         /* Modern Header Button */
         .header-btn {
             display: inline-flex;
             align-items: center;
             gap: 0.75rem;
             background: var(--white);
             color: var(--etrade-purple);
             padding: 0.75rem 1.5rem;
             border-radius: 25px;
             text-decoration: none;
             font-weight: 600;
             font-size: 0.95rem;
             transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
             box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
             border: 2px solid transparent;
         }
         
         .header-btn:hover {
             background: var(--etrade-purple);
             color: var(--white);
             transform: translateY(-2px);
             box-shadow: 0 8px 25px rgba(36, 16, 86, 0.2);
             border-color: var(--etrade-purple);
         }
         
         .header-btn:active {
             transform: translateY(0);
             box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
         }
         
         .header-btn-text {
             position: relative;
             z-index: 1;
         }
         
         .header-btn-icon {
             position: relative;
             z-index: 1;
             transition: transform 0.3s ease;
         }
         
         .header-btn:hover .header-btn-icon {
             transform: translateX(3px);
         }
         
         .action-panel {
             grid-column: 1 / -1;
             background: var(--white);
             border: 2px solid var(--gray-200);
             color: var(--gray-800);
         }
         
         .action-panel .panel-title {
             color: var(--white);
             border-bottom-color: rgba(255, 255, 255, 0.2);
         }
         
         .form-group {
             margin-bottom: 1.5rem;
         }
         
         .form-group:last-child {
             margin-bottom: 0;
         }
         
         /* Security Panel Styles */
         .security-panel {
             background: #FEFBF3;
             border: 2px solid #E5E7EB;
             border-radius: 16px;
         }
         
         .security-panel .panel-title {
             color: #374151;
             border-bottom: 2px solid #E5E7EB;
             margin-bottom: 1.5rem;
             padding-bottom: 1rem;
         }
         
         .security-info {
             display: flex;
             flex-direction: column;
             gap: 1.5rem;
         }
         
         .security-item {
             display: flex;
             align-items: flex-start;
             gap: 1rem;
             padding: 1rem;
             background: #FFFFFF;
             border-radius: 12px;
             border: 1px solid #F3F4F6;
             box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
         }
         
         .security-icon {
             color: #F59E0B;
             font-size: 1.3rem;
             margin-top: 0.1rem;
             flex-shrink: 0;
             background: #FEF3C7;
             padding: 0.5rem;
             border-radius: 8px;
         }
         
         .security-content {
             color: #374151;
             line-height: 1.6;
         }
         
         .security-content strong {
             color: #1F2937;
             font-size: 1.1rem;
             display: block;
             margin-bottom: 0.5rem;
         }
         
         .security-content p {
             margin: 0;
             color: #6B7280;
         }
         
         /* Title Styles */
         .title-main {
             display: inline;
             font-weight: 700;
         }
         
         .title-highlight {
             display: inline;
             font-weight: 700;
             color: white;
             position: relative;
         }
         
         .title-highlight::after {
             content: '';
             position: absolute;
             bottom: -2px;
             left: 0;
             right: 0;
             height: 2px;
             background: var(--etrade-purple-light);
             border-radius: 1px;
         }
         
         /* Mobile title adjustments */
         @media (max-width: 768px) {
             .h1 {
                 font-size: 2rem;
                 line-height: 1.2;
             }
         }

         /* Timeframe Selector Styles */
         .timeframe-selector {
             display: flex;
             background: var(--gray-100);
             border-radius: 12px;
             padding: 4px;
             gap: 2px;
             border: 2px solid var(--gray-200);
             position: relative;
             overflow: hidden;
         }
         
         .timeframe-btn {
             flex: 1;
             background: transparent;
             border: none;
             border-radius: 8px;
             padding: 12px 16px;
             font-weight: 600;
             font-size: 0.9rem;
             color: var(--gray-600);
             cursor: pointer;
             transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
             position: relative;
             min-width: 0;
             text-align: center;
         }
         
         .timeframe-btn:hover {
             background: rgba(86, 39, 216, 0.1);
             color: var(--etrade-purple);
             transform: translateY(-1px);
         }
         
         .timeframe-btn.active {
             background: var(--etrade-purple-light);
             color: var(--white);
             box-shadow: 0 4px 12px rgba(86, 39, 216, 0.3);
             transform: translateY(-1px);
         }
         
         .timeframe-btn.active::before {
             content: '';
             position: absolute;
             top: -2px;
             left: -2px;
             right: -2px;
             bottom: -2px;
             background: linear-gradient(135deg, var(--etrade-purple-light), var(--etrade-purple));
             border-radius: 10px;
             z-index: -1;
             opacity: 0.8;
             animation: glow 2s ease-in-out infinite alternate;
         }
         
         @keyframes glow {
             from {
                 box-shadow: 0 0 5px rgba(86, 39, 216, 0.5);
             }
             to {
                 box-shadow: 0 0 20px rgba(86, 39, 216, 0.8), 0 0 30px rgba(86, 39, 216, 0.4);
             }
         }
         
         /* Mobile responsive */
         @media (max-width: 768px) {
             .timeframe-selector {
                 overflow-x: auto;
                 scrollbar-width: none;
                 -ms-overflow-style: none;
             }
             
             .timeframe-selector::-webkit-scrollbar {
                 display: none;
             }
             
             .timeframe-btn {
                 flex-shrink: 0;
                 min-width: 60px;
                 padding: 10px 12px;
                 font-size: 0.8rem;
             }
         }

                 /* Banner Image Styles */
         .hero-section img {
             max-width: 100%;
             height: auto;
             object-fit: cover;
             border-radius: 12px;
             box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
         }

         @media (max-width: 768px) {
             .col-md-6, .col-md-4 { flex: 0 0 100%; max-width: 100%; }
             .form-container { margin: 1rem; border-radius: 16px; }
             .form-section, .results-section { padding: 2rem 1rem; }
             
             /* Mobile panel layout */
             .panel-group {
                 grid-template-columns: 1fr;
                 gap: 1rem;
             }
             
             .panel {
                 padding: 1rem;
             }
             
             /* Mobile banner adjustments */
             .hero-section img {
                 max-width: 80%;
                 margin: 2rem auto;
                 display: block;
             }
             
             /* Mobile asset button grid */
             .asset-button-grid {
                 grid-template-columns: repeat(2, 1fr);
                 gap: 0.5rem;
             }
             
             .asset-btn {
                 padding: 0.75rem 0.5rem;
                 font-size: 0.9rem;
                 min-height: 70px;
             }
             
             .asset-btn i {
                 font-size: 1.2rem;
             }
         }
    </style>
</head>

<body>
    <!-- Page wrapper -->
    <div class="flex flex-col min-h-screen overflow-hidden">



        <!-- Page content -->
        <main class="grow">

            <!-- Hero -->
            <section class="hero-section relative">
                <div class="max-w-6xl mx-auto px-4 sm:px-6">
                    <div class="pt-8 md:pt-12 md:pb-20">

                        <!-- Hero content -->
                        <div class="relative max-w-xl mx-auto md:max-w-none text-center md:text-left">
                        
                                                    <!-- Content -->
                        <div class="md:w-[800px] mx-auto text-center">

                                <!-- Copy -->
                                <h1 class="h1 text-white mb-6">
                                    <div class="text-center">
                                        
                                    </div>
                                    <div style="display: flex; align-items: center; justify-content: center; gap: 0rem; margin-bottom: 0.5rem;">
                                        <img src="assets/darklogo.png" alt="QuantAgent Logo" style="width: 7rem; height: 7rem; object-fit: contain; background: transparent; box-shadow: none; border: none; border-radius: 0; transform: translateY(0.5rem);">
                                        <span style="font-size: 4.0rem; font-weight: 700; color: white; line-height: 1.0;">QuantAgent:</span>
                                    </div>
                                    <div class="text-center">
                                        <span class="title-highlight">Multi-Agent Trading System</span>
                                    </div>
                                </h1>
                                <p class="text-lg text-white mb-8" style="font-size: 1.3rem; margin-top: 1.5rem;">Advanced multi-agent system combining technical indicators, pattern recognition, and trend analysis for comprehensive market insights.</p>

                                <!-- Buttons -->
                                <div class="max-w-xs mx-auto sm:max-w-none sm:flex sm:justify-center mb-12 md:mb-0">
                                    <div>
                                        <a class="hero-btn" href="#analysis">
                                            <span class="hero-btn-text">Start Analysis</span>
                                            <span class="hero-btn-icon">
                                                <i class="fas fa-arrow-right"></i>
                                            </span>
                                        </a>
                                    </div>
                                </div>
                                
                            </div>
                        
                            <!-- Parent container with relative positioning -->
                <!-- <div class="w-full md:w-[500px] mt-10 md:mt-0 md:ml-10 flex-shrink-0">
                        <img src="assets/banner.png" alt="QuantAgent Banner" class="w-full h-auto rounded-lg shadow-xl" />
                    </div> -->

                        
                        </div>

                    </div>
                </div>
            </section>

                        <!-- Analysis Form Section -->
            <section id="analysis" class="py-12 md:py-20">
                <div class="form-container">
                    <!-- Analysis Form -->
                    <div class="form-section">
                        <h3 style="text-align: center; font-size: 1.6rem; font-weight: 600; color: var(--etrade-purple); margin-bottom: 2rem; display: flex; align-items: center; justify-content: center; gap: 0.75rem;">
                            <i class="fas fa-cog" style="font-size: 1.5rem; color: var(--etrade-purple-light);"></i> Analysis Configuration
                        </h3>
                        
                        <!-- Panel 1: Data Selection -->
                        <div class="panel-group">
                            <div class="panel">
                                <h4 class="panel-title">
                                    <i class="fas fa-database"></i> Data Selection
                                </h4>
                                
                                <!-- Asset Selection -->
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="fas fa-coins"></i> Asset
                                    </label>
                                    <div class="asset-button-grid" id="assetButtonGrid">
                                        <button type="button" class="asset-btn" data-asset="BTC" onclick="selectAsset(this, 'BTC')">
                                            <i class="fas fa-bitcoin"></i> BTC
                                        </button>
                                        <button type="button" class="asset-btn" data-asset="ETH" onclick="selectAsset(this, 'ETH')">
                                            <i class="fab fa-ethereum"></i> ETH
                                        </button>
                                        <button type="button" class="asset-btn" data-asset="AAPL" onclick="selectAsset(this, 'AAPL')">
                                            <i class="fas fa-apple-alt"></i> AAPL
                                        </button>
                                        <button type="button" class="asset-btn" data-asset="GOOGL" onclick="selectAsset(this, 'GOOGL')">
                                            <i class="fab fa-google"></i> GOOGL
                                        </button>
                                        <button type="button" class="asset-btn" data-asset="MSFT" onclick="selectAsset(this, 'MSFT')">
                                            <i class="fab fa-microsoft"></i> MSFT
                                        </button>
                                        <button type="button" class="asset-btn" data-asset="TSLA" onclick="selectAsset(this, 'TSLA')">
                                            <i class="fas fa-car"></i> TSLA
                                        </button>
                                        <button type="button" class="asset-btn custom-asset-btn" id="customAssetBtn" onclick="showCustomAssetInput()">
                                            <i class="fas fa-plus"></i> Custom
                                        </button>
                                    </div>
                                    
                                    <!-- Custom Asset Input -->
                                    <div id="customAssetDiv" class="mt-3" style="display: none;">
                                        <div class="alert alert-info">
                                            <h6><i class="fas fa-plus-circle"></i> Custom Asset Symbol</h6>
                                            <p class="mb-2"><strong>💡 Examples:</strong> NQ (Nasdaq-100 Futures), ZN (10-Year Treasury), etc.</p>
                                            <p class="mb-0"><strong>📝 Format:</strong> Enter the Yahoo Finance symbol for your asset</p>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="customAssetInput" placeholder="Enter symbol (e.g., NQ=F, ZN=F, ^VIX)">
                                            <button class="btn btn-outline-primary" type="button" onclick="confirmCustomAsset()">
                                                <i class="fas fa-check"></i> Confirm
                                            </button>
                                        </div>
                                        <small class="form-text text-muted">Use Yahoo Finance symbols. For futures, add =F suffix (e.g., NQ=F)</small>
                                    </div>
                                </div>
                                
                                <!-- Timeframe Selection -->
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="fas fa-chart-line"></i> Timeframe
                                    </label>
                                    <div class="timeframe-selector">
                                        <button type="button" class="timeframe-btn" data-timeframe="1m" onclick="selectTimeframe(this, '1m')">
                                            1m
                                        </button>
                                        <button type="button" class="timeframe-btn" data-timeframe="15m" onclick="selectTimeframe(this, '15m')">
                                            15m
                                        </button>
                                        <button type="button" class="timeframe-btn" data-timeframe="1h" onclick="selectTimeframe(this, '1h')">
                                            1h
                                        </button>
                                        <button type="button" class="timeframe-btn" data-timeframe="4h" onclick="selectTimeframe(this, '4h')">
                                            4h
                                        </button>
                                        <button type="button" class="timeframe-btn" data-timeframe="1d" onclick="selectTimeframe(this, '1d')">
                                            1d
                                        </button>
                                        <button type="button" class="timeframe-btn" data-timeframe="1w" onclick="selectTimeframe(this, '1w')">
                                            1w
                                        </button>
                                        <button type="button" class="timeframe-btn" data-timeframe="1mo" onclick="selectTimeframe(this, '1mo')">
                                            1mo
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Panel 2: Date & Time Configuration -->
                            <div class="panel">
                                <h4 class="panel-title">
                                    <i class="fas fa-calendar-alt"></i> Date & Time Configuration
                                </h4>
                                
                                <!-- Date Range -->
                                <div class="form-group">
                                    <label class="form-label" style="font-size: 1.2rem; font-weight: 600; color: #374151; margin-bottom: 0.75rem;">
                                        <i class="fas fa-calendar-week" style="color: #6B7280; margin-right: 0.5rem;"></i> Date Range
                                    </label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <input type="date" id="startDate" class="form-control" placeholder="mm/dd/yyyy" required style="font-size: 1.1rem; padding: 0.875rem 1rem; border: 2px solid #E5E7EB; border-radius: 8px;">
                                        </div>
                                        <div class="col-md-6">
                                            <input type="date" id="endDate" class="form-control" placeholder="mm/dd/yyyy" required style="font-size: 1.1rem; padding: 0.875rem 1rem; border: 2px solid #E5E7EB; border-radius: 8px;">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Time Selector -->
                                <div class="form-group">
                                    <label class="form-label" style="font-size: 1.2rem; font-weight: 600; color: #374151; margin-bottom: 0.75rem;">
                                        <i class="fas fa-clock" style="color: #6B7280; margin-right: 0.5rem;"></i> Time Selector
                                    </label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <input type="time" id="startTime" class="form-control" value="00:00" step="60" style="font-size: 1.1rem; padding: 0.875rem 1rem; border: 2px solid #E5E7EB; border-radius: 8px;">
                                        </div>
                                        <div class="col-md-6">
                                            <input type="time" id="endTime" class="form-control" value="23:59" step="60" style="font-size: 1.1rem; padding: 0.875rem 1rem; border: 2px solid #E5E7EB; border-radius: 8px;">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Current Time Option -->
                                <div class="form-group">
                                    <div class="form-check" style="margin-top: 1rem;">
                                        <input class="form-check-input" type="checkbox" id="useCurrentTime" checked style="transform: scale(1.2); margin-right: 0.75rem;">
                                        <label class="form-check-label" for="useCurrentTime" style="font-size: 1.3rem; font-weight: 500; color: #374151; cursor: pointer;">
                                            Use current date & time for end
                                        </label>
                                    </div>
                                </div>
                                
                                <!-- Validation Messages -->
                                <div id="dateRangeInfo" class="alert alert-info mt-2" style="display: none;">
                                    <i class="fas fa-info-circle"></i>
                                    <span id="dateRangeText"></span>
                                </div>
                                
                                <div id="dateRangeError" class="alert alert-danger mt-2" style="display: none;">
                                    <i class="fas fa-exclamation-triangle"></i>
                                    <span id="dateRangeErrorText"></span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Panel 3: Settings & Security -->
                        <div class="panel-group">
                            <div class="panel">
                                <h4 class="panel-title">
                                    <i class="fas fa-cog"></i> Settings
                                </h4>
                                
                                <!-- OpenAI API Key Input -->
                                <div class="form-group">
                                    <label class="form-label">OpenAI API Key</label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" id="apiKeyInput" placeholder="Enter your OpenAI API key">
                                        <button class="btn btn-outline-primary" type="button" onclick="updateApiKey()">
                                            <i class="fas fa-save"></i> Update
                                        </button>
                                    </div>
                                    
                                    <!-- API Key Status Messages -->
                                    <div id="apiKeyStatus" class="alert alert-info mt-2" style="display: none;">
                                        <i class="fas fa-info-circle"></i>
                                        <span id="apiKeyStatusText"></span>
                                    </div>
                                    <div id="apiKeyError" class="alert alert-danger mt-2" style="display: none;">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <span id="apiKeyErrorText"></span>
                                    </div>
                                    <div id="apiKeySuccess" class="alert alert-success mt-2" style="display: none;">
                                        <i class="fas fa-check-circle"></i>
                                        <span id="apiKeySuccessText"></span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Security Information Panel -->
                            <div class="panel security-panel">
                                <h4 class="panel-title">
                                    <i class="fas fa-shield-alt"></i> Security Information
                                </h4>
                                
                                <div class="security-info">
                                    <div class="security-item">
                                        <i class="fas fa-server security-icon"></i>
                                        <div class="security-content">
                                            <strong>Localhost Only</strong>
                                            <p>This server runs exclusively on localhost (127.0.0.1)</p>
                                        </div>
                                    </div>
                                    
                                    <div class="security-item">
                                        <i class="fas fa-key security-icon"></i>
                                        <div class="security-content">
                                            <strong>API Key Security</strong>
                                            <p>Your API key is stored locally and never uploaded to external servers</p>
                                        </div>
                                    </div>
                                    
                                    <div class="security-item">
                                        <i class="fas fa-shield-alt security-icon"></i>
                                        <div class="security-content">
                                            <strong>Data Privacy</strong>
                                            <p>All analysis data remains on your local machine</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Run Analysis Button -->
                        <div class="text-center" style="margin-top: 2rem;">
                            <button class="btn btn-primary btn-lg" id="analyzeBtn" onclick="runAnalysis()" style="padding: 1.5rem 3rem; font-size: 1.3rem; border-radius: 15px;">
                                <i class="fas fa-play"></i> Run Analysis
                            </button>
                        </div>
                    </div>
                </div>
            </section>

        </main>

    </div>

    <script>
        // Global variables
        let currentAsset = '';
        let currentTimeframe = '';
        
        // Persisted state keys
        const STORAGE_KEYS = {
            CUSTOM_ASSETS: 'quantagent_custom_assets',
            SELECTED_ASSET: 'quantagent_selected_asset',
            SELECTED_TIMEFRAME: 'quantagent_selected_timeframe'
        };

        // Add or render a custom asset button into the grid
        function addCustomAssetButton(symbol, isServerLoaded = false) {
            const grid = document.getElementById('assetButtonGrid');
            if (!grid) return;

            // Prevent duplicates (check existing data-asset values)
            const existing = Array.from(grid.querySelectorAll('.asset-btn')).some(btn => btn.dataset.asset === symbol);
            if (existing) return;

            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'asset-btn';
            btn.dataset.asset = symbol;
            btn.innerHTML = `<i class="fas fa-tag"></i> ${symbol}`;
            btn.addEventListener('click', () => selectAsset(btn, symbol));

            // Insert before the "Custom" button if present
            const customBtn = document.getElementById('customAssetBtn');
            if (customBtn && customBtn.parentNode === grid) {
                grid.insertBefore(btn, customBtn);
            } else {
                grid.appendChild(btn);
            }

            // If loaded from server or localStorage, do not auto-select unless it matches stored selection
            const storedSelected = localStorage.getItem(STORAGE_KEYS.SELECTED_ASSET);
            if (storedSelected === symbol) {
                // mimic click to set active and store
                btn.click();
            }
        }

        // Load custom assets from localStorage and server, render them
        function loadCustomAssets() {
            // Load from localStorage first (fast)
            try {
                const local = localStorage.getItem(STORAGE_KEYS.CUSTOM_ASSETS);
                if (local) {
                    const list = JSON.parse(local);
                    list.forEach(sym => addCustomAssetButton(sym, false));
                }
            } catch (e) {
                console.warn('Failed to parse local custom assets', e);
            }

            // Then attempt to load server-persisted custom assets and merge
            fetch('/api/custom-assets')
                .then(r => r.json())
                .then(data => {
                    if (Array.isArray(data.custom_assets)) {
                        data.custom_assets.forEach(sym => addCustomAssetButton(sym, true));
                        // Sync server list into localStorage (merge, dedupe)
                        try {
                            const local = JSON.parse(localStorage.getItem(STORAGE_KEYS.CUSTOM_ASSETS) || '[]');
                            const merged = Array.from(new Set([...(local || []), ...data.custom_assets]));
                            localStorage.setItem(STORAGE_KEYS.CUSTOM_ASSETS, JSON.stringify(merged));
                        } catch (e) {
                            console.warn('Failed to sync custom assets to localStorage', e);
                        }
                    }
                })
                .catch(err => {
                    // Not fatal - server might not be reachable
                    console.warn('Could not fetch server custom assets', err);
                });
        }

        // Override confirmCustomAsset to create a persistent custom asset and persist to server/localStorage
        function confirmCustomAsset() {
            const customAssetEl = document.getElementById('customAssetInput');
            const customAsset = customAssetEl.value.trim();

            if (!customAsset) {
                alert('Please enter a custom asset symbol.');
                return;
            }

            // Normalize (trim)
            const symbol = customAsset;

            // Save to localStorage list
            try {
                const listRaw = localStorage.getItem(STORAGE_KEYS.CUSTOM_ASSETS);
                const list = listRaw ? JSON.parse(listRaw) : [];
                if (!list.includes(symbol)) {
                    list.push(symbol);
                    localStorage.setItem(STORAGE_KEYS.CUSTOM_ASSETS, JSON.stringify(list));
                }
            } catch (e) {
                console.warn('Could not persist custom asset to localStorage', e);
            }

            // Persist to server (best-effort)
            fetch('/api/save-custom-asset', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ symbol })
            }).then(r => r.json())
              .then(resp => {
                  if (!resp.success) {
                      console.warn('Server did not save custom asset', resp);
                  }
              }).catch(err => {
                  console.warn('Error saving custom asset to server', err);
              });

            // Add button and select it
            addCustomAssetButton(symbol);
            // Select the new asset: find button and click
            const grid = document.getElementById('assetButtonGrid');
            const newBtn = Array.from(grid.querySelectorAll('.asset-btn')).find(b => b.dataset.asset === symbol);
            if (newBtn) {
                newBtn.click();
            }

            // Hide custom asset input
            document.getElementById('customAssetDiv').style.display = 'none';

            // Clear input
            customAssetEl.value = '';

            // Notify user
            // Use a non-blocking notification (replace alert with console + subtle DOM message if desired)
            console.log(`Custom asset "${symbol}" selected and persisted`);
        }

        // Updated selectAsset to persist selection to localStorage
        function selectAsset(button, asset) {
            // Remove active class from all asset buttons
            document.querySelectorAll('.asset-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            // Add active class to clicked button
            button.classList.add('active');

            // Store selected asset
            selectedAsset = asset;
            try {
                localStorage.setItem(STORAGE_KEYS.SELECTED_ASSET, asset);
            } catch (e) {
                console.warn('Could not persist selected asset', e);
            }

            // Hide custom asset input if it was showing
            const cav = document.getElementById('customAssetDiv');
            if (cav) cav.style.display = 'none';

            console.log('Selected asset:', asset);
        }

        // Persist timeframe selection as well
        function selectTimeframe(button, timeframe) {
            // Remove active class from all timeframe buttons
            document.querySelectorAll('.timeframe-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            // Add active class to clicked button
            button.classList.add('active');

            // Store selected timeframe
            selectedTimeframe = timeframe;
            try {
                localStorage.setItem(STORAGE_KEYS.SELECTED_TIMEFRAME, timeframe);
            } catch (e) {
                console.warn('Could not persist selected timeframe', e);
            }

            console.log('Selected timeframe:', timeframe);
        }

        // On page load, restore selected asset/timeframe and custom assets
        document.addEventListener('DOMContentLoaded', function() {
            // Set default dates
            const now = new Date();
            const thirtyDaysAgo = new Date(now.getTime() - (30 * 24 * 60 * 60 * 1000));
            
            // Format dates for input fields
            const formatDate = (date) => {
                return date.toISOString().split('T')[0];
            };
            
            // Set default start date (30 days ago)
            document.getElementById('startDate').value = formatDate(thirtyDaysAgo);
            
            // Set default end date (today)
            document.getElementById('endDate').value = formatDate(now);
            
            // Apply the current-time checkbox behavior immediately on load
            // (this will disable & populate end date/time if the checkbox is checked by default)
            try { handleUseCurrentTimeChange(); } catch (e) { console.warn('handleUseCurrentTimeChange not available yet', e); }
            
            // Load custom assets and server-synced assets
            loadCustomAssets();

            // Restore selected timeframe (if saved)
            try {
                const savedTF = localStorage.getItem(STORAGE_KEYS.SELECTED_TIMEFRAME);
                if (savedTF) {
                    const tfBtn = Array.from(document.querySelectorAll('.timeframe-btn')).find(b => b.dataset.timeframe === savedTF);
                    if (tfBtn) {
                        tfBtn.classList.add('active');
                        selectedTimeframe = savedTF;
                    }
                }
            } catch (e) {
                console.warn('Could not restore timeframe from localStorage', e);
            }

            // Restore selected asset (if saved). If it is a custom asset that hasn't been added yet,
            // add it and then select it (addCustomAssetButton handles checking duplicates).
            try {
                const savedAsset = localStorage.getItem(STORAGE_KEYS.SELECTED_ASSET);
                if (savedAsset) {
                    // Try to find an existing button
                    let btn = Array.from(document.querySelectorAll('.asset-btn')).find(b => b.dataset.asset === savedAsset);
                    if (!btn) {
                        // Add it as custom and then select
                        addCustomAssetButton(savedAsset, false);
                        btn = Array.from(document.querySelectorAll('.asset-btn')).find(b => b.dataset.asset === savedAsset);
                    }
                    if (btn) {
                        btn.classList.add('active');
                        selectedAsset = savedAsset;
                    }
                } else {
                    // fallback defaults from original code
                    const defaultTimeframeBtn = document.querySelector('[data-timeframe="1h"]');
                    if (defaultTimeframeBtn && !selectedTimeframe) {
                        defaultTimeframeBtn.classList.add('active');
                        selectedTimeframe = '1h';
                    }
                    const defaultAssetBtn = document.querySelector('[data-asset="BTC"]');
                    if (defaultAssetBtn && !selectedAsset) {
                        defaultAssetBtn.classList.add('active');
                        selectedAsset = 'BTC';
                    }
                }
            } catch (e) {
                console.warn('Could not restore selected asset from localStorage', e);
            }

            document.getElementById('useCurrentTime').addEventListener('change', handleUseCurrentTimeChange);
            
            // Set up date/time validation
            const dateInputs = ['startDate', 'startTime', 'endDate', 'endTime'];
            dateInputs.forEach(id => {
                document.getElementById(id).addEventListener('change', validateDateRange);
            });
            
            // Initialize current time update
            setInterval(updateCurrentTime, 1000);
            
            // Add keyboard navigation for timeframe selector
            document.addEventListener('keydown', function(e) {
                const activeBtn = document.querySelector('.timeframe-btn.active');
                if (!activeBtn) return;
                
                const buttons = Array.from(document.querySelectorAll('.timeframe-btn'));
                const currentIndex = buttons.indexOf(activeBtn);
                
                if (e.key === 'ArrowLeft' && currentIndex > 0) {
                    buttons[currentIndex - 1].click();
                } else if (e.key === 'ArrowRight' && currentIndex < buttons.length - 1) {
                    buttons[currentIndex + 1].click();
                }
            });
            
            // Check API key status on page load
            checkApiKeyStatus();
        });
        
        function checkApiKeyStatus() {
            fetch('/api/get-api-key-status')
                .then(response => response.json())
                .then(data => {
                    if (data.has_key) {
                        showApiKeyStatus(`API key is set: ${data.masked_key}`);
                    } else {
                        showApiKeyError('No API key found. Please enter your OpenAI API key.');
                    }
                })
                .catch(error => {
                    console.error('Error checking API key status:', error);
                    showApiKeyError('Unable to check API key status');
                });
        }
        
                 // Global variables
         let selectedAsset = '';
         let selectedTimeframe = '1h'; // Default timeframe
         
         function selectAsset(button, asset) {
             // Remove active class from all asset buttons
             document.querySelectorAll('.asset-btn').forEach(btn => {
                 btn.classList.remove('active');
             });
             
             // Add active class to clicked button
             button.classList.add('active');
             
             // Store selected asset
             selectedAsset = asset;
             try {
                 localStorage.setItem(STORAGE_KEYS.SELECTED_ASSET, asset);
             } catch (e) {
                 console.warn('Could not persist selected asset', e);
             }

             // Hide custom asset input if it was showing
             const cav = document.getElementById('customAssetDiv');
             if (cav) cav.style.display = 'none';

             console.log('Selected asset:', asset);
         }
         
         function showCustomAssetInput() {
             // Remove active class from all asset buttons
             document.querySelectorAll('.asset-btn').forEach(btn => {
                 btn.classList.remove('active');
             });
             
             // Show custom asset input
             document.getElementById('customAssetDiv').style.display = 'block';
             document.getElementById('customAssetInput').focus();
             
             // Clear selected asset
             selectedAsset = '';
         }
         
         function confirmCustomAsset() {
             const customAssetEl = document.getElementById('customAssetInput');
             const customAsset = customAssetEl.value.trim();

             if (!customAsset) {
                 alert('Please enter a custom asset symbol.');
                 return;
             }

             // Normalize (trim)
             const symbol = customAsset;

             // Save to localStorage list
             try {
                 const listRaw = localStorage.getItem(STORAGE_KEYS.CUSTOM_ASSETS);
                 const list = listRaw ? JSON.parse(listRaw) : [];
                 if (!list.includes(symbol)) {
                     list.push(symbol);
                     localStorage.setItem(STORAGE_KEYS.CUSTOM_ASSETS, JSON.stringify(list));
                 }
             } catch (e) {
                 console.warn('Could not persist custom asset to localStorage', e);
             }

             // Persist to server (best-effort)
             fetch('/api/save-custom-asset', {
                 method: 'POST',
                 headers: { 'Content-Type': 'application/json' },
                 body: JSON.stringify({ symbol })
             }).then(r => r.json())
               .then(resp => {
                   if (!resp.success) {
                       console.warn('Server did not save custom asset', resp);
                   }
               }).catch(err => {
                   console.warn('Error saving custom asset to server', err);
               });

            // Add button and select it
            addCustomAssetButton(symbol);
            // Select the new asset: find button and click
            const grid = document.getElementById('assetButtonGrid');
            const newBtn = Array.from(grid.querySelectorAll('.asset-btn')).find(b => b.dataset.asset === symbol);
            if (newBtn) {
                newBtn.click();
            }

            // Hide custom asset input
            document.getElementById('customAssetDiv').style.display = 'none';

            // Clear input
            customAssetEl.value = '';

            // Notify user
            // Use a non-blocking notification (replace alert with console + subtle DOM message if desired)
            console.log(`Custom asset "${symbol}" selected and persisted`);
         }
        
                 function runAnalysis() {
             const dataSource = 'live'; // Always use live data
             const timeframe = selectedTimeframe;
             
             // Get asset value from selected asset
             let asset = selectedAsset;
             
             // Validate inputs
             if (!asset || !timeframe) {
                 alert('Please select both asset and timeframe.');
                 return;
             }
             
             // Get date and time values
             const startDate = document.getElementById('startDate').value;
             const startTime = document.getElementById('startTime').value;
             const endDate = document.getElementById('endDate').value;
             const endTime = document.getElementById('endTime').value;
             const useCurrentTime = document.getElementById('useCurrentTime').checked;
             
             // Validate dates
             if (!startDate || !endDate) {
                 alert('Please select both start and end dates.');
                 return;
             }
             
             // Show loading state
             const analyzeBtn = document.getElementById('analyzeBtn');
             const originalText = analyzeBtn.innerHTML;
             analyzeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Analyzing...';
             analyzeBtn.disabled = true;
             
             // Prepare request data
             const requestData = {
                 data_source: dataSource,
                 asset: asset,
                 timeframe: timeframe,
                 start_date: startDate,
                 start_time: startTime,
                 end_date: endDate,
                 end_time: endTime,
                 use_current_time: useCurrentTime,
                 redirect_to_output: true
             };
             
             // Make API call
             fetch('/api/analyze', {
                 method: 'POST',
                 headers: {
                     'Content-Type': 'application/json',
                 },
                 body: JSON.stringify(requestData)
             })
             .then(response => response.json())
             .then(data => {
                 if (data.redirect) {
                     // Redirect to output page with results
                     window.location.href = data.redirect;
                 } else if (data.error) {
                     // Show error message
                     alert('Analysis failed: ' + data.error);
                     // Reset button
                     analyzeBtn.innerHTML = originalText;
                     analyzeBtn.disabled = false;
                 } else {
                     // Handle other responses
                     console.log('Analysis completed:', data);
                     alert('Analysis completed successfully!');
                     // Reset button
                     analyzeBtn.innerHTML = originalText;
                     analyzeBtn.disabled = false;
                 }
             })
             .catch(error => {
                 console.error('Error:', error);
                 alert('An error occurred during analysis. Please try again.');
                 // Reset button
                 analyzeBtn.innerHTML = originalText;
                 analyzeBtn.disabled = false;
             });
        }
        
        function handleUseCurrentTimeChange() {
            const useCurrentTime = document.getElementById('useCurrentTime');
            const endTimeInput = document.getElementById('endTime');
            const endDateInput = document.getElementById('endDate');
            
            if (useCurrentTime.checked) {
                // Lock both end date and end time
                endTimeInput.disabled = true;
                endDateInput.disabled = true;
                endTimeInput.style.opacity = '0.5';
                endDateInput.style.opacity = '0.5';
                
                // Set to current date and time
                const now = new Date();
                const currentDate = now.toISOString().split('T')[0];
                const currentTime = now.toTimeString().slice(0, 5); // HH:MM format
                
                endDateInput.value = currentDate;
                endTimeInput.value = currentTime;
                
                // Add visual indication
                endDateInput.title = 'Locked: Using current date/time';
                endTimeInput.title = 'Locked: Using current date/time';
            } else {
                // Unlock both inputs
                endTimeInput.disabled = false;
                endDateInput.disabled = false;
                endTimeInput.style.opacity = '1';
                endDateInput.style.opacity = '1';
                
                // Remove visual indication
                endDateInput.title = '';
                endTimeInput.title = '';
            }
        }
        
        function updateCurrentTime() {
            const useCurrentTime = document.getElementById('useCurrentTime');
            if (useCurrentTime.checked) {
                const now = new Date();
                const currentDate = now.toISOString().split('T')[0];
                const currentTime = now.toTimeString().slice(0, 5); // HH:MM format
                
                document.getElementById('endDate').value = currentDate;
                document.getElementById('endTime').value = currentTime;
            }
        }
        
        function validateDateRange() {
            // Simple date validation
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            if (startDate && endDate && startDate > endDate) {
                document.getElementById('dateRangeError').style.display = 'block';
                document.getElementById('dateRangeErrorText').textContent = 'Start date cannot be after end date';
            } else {
                document.getElementById('dateRangeError').style.display = 'none';
            }
        }
        
        function hideDateValidation() {
            document.getElementById('dateRangeError').style.display = 'none';
            document.getElementById('dateRangeInfo').style.display = 'none';
        }
        
                 function updateTimeframeLimits() {
             // Placeholder for timeframe limits functionality
             console.log('Timeframe limits updated');
         }
         
         // API Key Management Functions
         function updateApiKey() {
             const apiKey = document.getElementById('apiKeyInput').value.trim();
             
             if (!apiKey) {
                 showApiKeyError('Please enter an API key');
                 return;
             }
             
             // Hide previous messages
             hideApiKeyMessages();
             
             // Show loading state
             const updateBtn = document.querySelector('button[onclick="updateApiKey()"]');
             const originalText = updateBtn.innerHTML;
             updateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
             updateBtn.disabled = true;
             
             // Make API call to update the key
             fetch('/api/update-api-key', {
                 method: 'POST',
                 headers: {
                     'Content-Type': 'application/json',
                 },
                 body: JSON.stringify({ api_key: apiKey })
             })
             .then(response => response.json())
             .then(data => {
                 if (data.success) {
                     showApiKeySuccess('API key updated successfully!');
                     document.getElementById('apiKeyInput').value = '';
                 } else {
                     showApiKeyError(data.error || 'Failed to update API key');
                 }
             })
             .catch(error => {
                 console.error('Error:', error);
                 showApiKeyError('An error occurred while updating the API key');
             })
             .finally(() => {
                 // Reset button
                 updateBtn.innerHTML = originalText;
                 updateBtn.disabled = false;
             });
         }
         
         function showApiKeySuccess(message) {
             const successDiv = document.getElementById('apiKeySuccess');
             const successText = document.getElementById('apiKeySuccessText');
             successText.textContent = message;
             successDiv.style.display = 'block';
             
             // Hide after 5 seconds
             setTimeout(() => {
                 successDiv.style.display = 'none';
             }, 5000);
         }
         
         function showApiKeyError(message) {
             const errorDiv = document.getElementById('apiKeyError');
             const errorText = document.getElementById('apiKeyErrorText');
             errorText.textContent = message;
             errorDiv.style.display = 'block';
             
             // Hide after 5 seconds
             setTimeout(() => {
                 errorDiv.style.display = 'none';
             }, 5000);
         }
         
         function hideApiKeyMessages() {
             document.getElementById('apiKeyError').style.display = 'none';
             document.getElementById('apiKeySuccess').style.display = 'none';
         }
    </script>
</body>
</html>
